<template>
  <div class="editor-container">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editor"
      :default-config="toolbarConfigFormat"
      :mode="mode"
    />
    <Editor
      ref="editorRef"
      v-model="richText"
      :default-config="editorConfigFormat"
      :mode="mode"
      style="height: 300px; overflow-y: hidden;"
      @onChange="handleOnChange"
      @onCreated="handleCreated"
      @onBlur="handleOnBlur"
    />
  </div>
</template>

<script>
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import emitter from 'element-ui/src/mixins/emitter'
import { Boot } from '@wangeditor/editor'

/**
 * 由于富文本编辑的默认值不为空（”<p><br></p>“）
 * 导致进行表单校验时无法校验是否有输入内容
 * 所以再次注册一个插件来进行判断是否存在有效值
 */
Boot.registerPlugin(withEmptyHtml)
function withEmptyHtml(editor) {
  const { getHtml } = editor
  const newEditor = editor

  newEditor.getHtml = () => {
    if (newEditor.isEmpty()) {
      return ''
    }
    return getHtml()
  }

  return newEditor
}
export default {
  name: 'RichTextEditor',
  components: {
    Editor,
    Toolbar
  },
  mixins: [emitter],
  props: {
    value: {
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      default: '请输入内容'
    },
    disabled: {
      type: Boolean,
      default: false
    },
    toolbarKeys: {
      type: Array,
      default: () => []
    },
    showUploadImage: {
      type: Boolean,
      default: false
    }
  },
  inject: {
    elForm: {
      default: ''
    },
    elFormItem: {
      default: ''
    }
  },
  data() {
    return {
      editor: null,
      richText: '',
      mode: 'default',
      editorConfig: {
        placeholder: this.placeholder,
        readOnly: this.disabled,
        autoFocus: false
      },
      toolbarConfig: {
        toolbarKeys: [
          'headerSelect',
          'blockquote',
          '|',
          'bold',
          'underline',
          'italic',
          'through',
          'color',
          'bgColor',
          '|',
          'bulletedList',
          'numberedList',
          'todo',
          '|',
          'indent',
          '|',
          'justifyLeft',
          'justifyRight',
          'justifyCenter',
          '|',
          'insertLink',
          'insertTable',
          'uploadImage',
          '|',
          'undo',
          'redo'
        ]
      }
    }
  },
  computed: {
    toolbarConfigFormat() {
      const toolbar = this.toolbarConfig
      if (this.toolbarKeys.length > 0) {
        toolbar.toolbarKeys.push(...this.toolbarKeys)
      }
      return toolbar
    },

    editorConfigFormat() {
      const editor = this.editorConfig
      editor.MENU_CONF = {}

      if (this.showUploadImage) {
        editor.MENU_CONF.uploadImage = this.getUploadConfig()
      }

      return editor
    }
  },
  watch: {
    richText(newVal) {
      this.$emit('input', newVal)
    }
  },
  mounted() {

  },
  methods: {

    handleCreated(editor) {
      this.editor = Object.seal(editor)
      this.$nextTick(() => {
        this.richText = this.value
      })
    },

    handleOnBlur() {
      this.$emit('blur')
      this.dispatch('ElFormItem', 'el.form.blur', [this.richText])
    },

    handleOnChange() {
      this.$emit('change', this.richText)
      this.dispatch('ElFormItem', 'el.form.change', [this.richText])
    },

    getUploadConfig() {
      const maxFileSize = 1024 * 1024 * 2
      const that = this
      return {
        server: `${process.env.VUE_APP_UPLOAD}api/v1/upload/file`,
        fieldName: 'file',
        maxFileSize,
        allowedFileTypes: ['image/*'],

        onSuccess(file, res) {
          that.$message.success('图片上传成功')
        },

        onError(file, err) {
          if (file.size > maxFileSize) {
            that.$message.error(`上传图片不能大于${maxFileSize / 1024 / 1024}M`)
          } else {
            that.$message.error('图片上传出错，请重试')
          }
        },

        customInsert(res, insertFn) {
          console.log('res customInsert--------->', res)
          insertFn(res.data.path, res.data.name, res.data.path)
        }
      }
    },

    clearEditorContent() {
      this.editor.clear()
    }

  }
}
</script>

<style lang="scss" scoped>
.editor-container {
  border: 1px solid #ccc;
  z-index: 100;

  .editor {
    min-height: 300px;
    background-color: #fff;
  }
}
</style>
